package com.cg.bank.util;

import com.cg.bank.domain.Transaction;
import com.cg.bank.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理交易记录Map结果集
 *
 * @author chunge
 * @version 1.0
 */
public class TransactionListHandler implements ResultSetHander<List<Transaction>> {
    @Override
    public List<Transaction> handle(ResultSet resultSet) throws SQLException {
        if (resultSet.wasNull()) {
            return null;
        }
        int resultCount = resultSet.getMetaData().getColumnCount();
        List<String> columnCountList = new ArrayList<>();
        for (int i = 1; i <= resultCount; i++) {
            // 如未指定SQL AS，则getColumnLabel与getColumnName方法返回的值相同
            columnCountList.add(resultSet.getMetaData().getColumnLabel(i));
        }

        return processORM(resultSet, columnCountList);
    }

    /**
     * 处理对象关系映射
     *
     * @param resultSet       结果集
     * @param columnCountList 封装字段名list
     * @return user basic information 用户基本信息
     * @throws SQLException
     */
    private List<Transaction> processORM(ResultSet resultSet, List<String> columnCountList) throws SQLException {
        List<Transaction> resultList = new ArrayList<>();
        // 交易信息Bean
        Transaction transaction;
        // 用户信息Bean
        User user;
        while (resultSet.next()) {
            user = new User();
            transaction = new Transaction();
            transaction.setId(resultSet.getInt(columnCountList.get(0)));
            user.setAccount(resultSet.getString(columnCountList.get(1)));
            user.setUserName(resultSet.getString(columnCountList.get(2)));
            transaction.setTime(resultSet.getDate(columnCountList.get(3)));
            transaction.setType(resultSet.getString(columnCountList.get(4)));
            transaction.setMoney(resultSet.getDouble(columnCountList.get(5)));
            transaction.setDetail(resultSet.getString(columnCountList.get(6)));
            transaction.setBalance(resultSet.getDouble(columnCountList.get(7)));
            // 为translation装配关系
            transaction.setUser(user);
            // 保存本条交易记录到resultList
            resultList.add(transaction);
        }
        return resultList;
    }
}
